#!/usr/bin/env python3

import sys
import os
import time

import serial
import serial.tools.list_ports


class SerialSender:
  def __init__(self, port, baudrate=9600):
    self.ser = serial.Serial(port, baudrate)

  def send_data(self, data):
    try:
    # 将数据转换为十六进制字符串并发送
      hex_data = ' '.join(format(val, '02X') for val in data)
      self.ser.write(bytes.fromhex(hex_data))
      print(f"Sent data in hex: {hex_data}")
    except Exception as e:
      print(f"Error during sending data: {e}")

  def close_serial(self):
    self.ser.close()
   
   #发送小车电机驱动的函数
  def air_speed(self,array):
    for i in array:
      time.sleep(0)
      self.send_data([i])
  
  #发送小车移动多少距离的函数
  def air_distance(self,array):
    for i in array:
      time.sleep(0)
      self.send_data([i])
      
  #发送机械臂运动的函数
  def air_armmotion(self,array):
    for i in array:
      time.sleep(0)
      self.send_data([i])
  
  #发送小车移动多少距离的函数
  def air_GPS(self,array):
    for i in array:
      time.sleep(0)
      self.send_data([i])
      
  def air_change_serial(self,array):
    for i in array:
      time.sleep(0)
      self.send_data([i])
      
      
  def receive_integer(self):
    try:
      # 读取一个字节的数据
      received_byte = self.ser.read(1)
      if received_byte:
        # 将接收到的字节转换为整数
        received_integer = int.from_bytes(received_byte, byteorder='big')
        print(f"Received integer: {received_integer}")
        return received_integer
      else:
        print("No data received.")
        return None
    except Exception as e:
      print(f"Error during receiving data: {e}")
      return None

